const express = require('express');
const multer = require('multer');
const path = require('path');
const router = express.Router();

// 导入工具和中间件
const { success, error, badRequest, notFound, asyncHandler, paginated } = require('../utils/response');
const { authenticateToken } = require('../utils/auth');
const { validateFileType } = require('../utils/validation');

// 导入服务层
const detectionService = require('../services/detectionService');

// 配置文件上传
const storage = multer.memoryStorage();
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB
    files: 1
  },
  fileFilter: (req, file, cb) => {
    const allowedTypes = ['mp3', 'wav', 'm4a'];
    const validation = validateFileType(file, allowedTypes);
    if (validation.isValid) {
      cb(null, true);
    } else {
      cb(new Error(validation.message), false);
    }
  }
});

/**
 * 获取检测文本
 * GET /detection/texts
 */
router.get('/texts', asyncHandler(async (req, res) => {
  try {
    const texts = await detectionService.getDetectionTexts(req.query);
    success(res, texts);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 获取随机检测文本
 * GET /detection/texts/random
 */
router.get('/texts/random', asyncHandler(async (req, res) => {
  try {
    const text = await detectionService.getRandomDetectionText(req.query);
    success(res, text);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 提交语音评测
 * POST /detection/evaluate
 */
router.post('/evaluate', authenticateToken, upload.single('audioFile'), asyncHandler(async (req, res) => {
  const { textId, duration } = req.body;
  const audioFile = req.file;

  // 基本参数验证
  if (!textId || isNaN(parseInt(textId))) {
    return badRequest(res, '无效的文本ID');
  }

  if (!audioFile) {
    return badRequest(res, '请上传音频文件');
  }

  if (!duration || isNaN(parseFloat(duration))) {
    return badRequest(res, '请提供录音时长');
  }

  try {
    const result = await detectionService.submitAudioEvaluation(
      req.user.id,
      parseInt(textId),
      audioFile,
      parseFloat(duration)
    );
    success(res, result, '评测完成');
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 获取评测历史
 * GET /detection/history
 */
router.get('/history', authenticateToken, asyncHandler(async (req, res) => {
  const result = await detectionService.getEvaluationHistory(req.user.id, req.query);
  paginated(res, result.list, result.total, result.page, result.limit, { statistics: result.statistics });
}));

/**
 * 获取评测详情
 * GET /detection/history/:id
 */
router.get('/history/:id', authenticateToken, asyncHandler(async (req, res) => {
  const { id } = req.params;

  if (!id || isNaN(parseInt(id))) {
    return badRequest(res, '无效的评测记录ID');
  }

  try {
    const detail = await detectionService.getEvaluationDetail(req.user.id, parseInt(id));
    success(res, detail);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

/**
 * 获取评测排行榜
 * GET /detection/leaderboard
 */
router.get('/leaderboard', asyncHandler(async (req, res) => {
  try {
    const leaderboard = await detectionService.getLeaderboard(req.query);
    success(res, leaderboard);
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

module.exports = router;
